package com.ten.service.webSocket;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSONObject;
import com.ten.pojo.Message;
public class MyWebSocketHandler implements WebSocketHandler{
	private static int onlineCount=0;
	private static final Map<String,WebSocketSession> userMap = new HashMap<>();
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		addOnlineCount();
		String username =(String) session.getAttributes().get("WEBSOCKET_USERNAME");
		userMap.put(username, session);
	}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		Message msg =new Message();
		String username =(String) session.getAttributes().get("WEBSOCKET_USERNAME");
		msg.setFromUser(username);
		msg.setSendTime(new Date());
		msg.setTextMessage((String)message.getPayload());
		TextMessage returnMessage = new TextMessage(JSONObject.toJSONString(msg));
		//session.sendMessage(returnMessage);
		this.sendMessagesToUsers(returnMessage);
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		System.out.println(exception);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		// TODO Auto-generated method stub
		subOnlineCount();
		String username =(String) session.getAttributes().get("WEBSOCKET_USERNAME");
		userMap.remove(username);
	}

	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}
	private static synchronized void addOnlineCount(){
		onlineCount++;
	}
	
	private static synchronized void subOnlineCount(){
		onlineCount--;
	}
	
	private static synchronized int getOnlineCount(){
		return onlineCount;
	}
	
	/**
	 * 给所有的用户发送消息
	 */
	public void sendMessagesToUsers(TextMessage message){
		Collection<WebSocketSession> sessionSet =userMap.values();
		for(WebSocketSession user : sessionSet){
			if(user.isOpen()){
				try {
					user.sendMessage(message);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 发送消息给指定的用户
	 */
	public void sendMessageToUser(String username,TextMessage message){
		WebSocketSession userSession =userMap.get(username);
		if(userSession.isOpen()){
			try {
				userSession.sendMessage(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
